package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.sun.jna.platform.win32.DdemlUtil;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备状态Service业务层处理
 * 
 * @author huangqin
 * @date 2025-05-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;


/**
     * 查询设备状态
     *
     * @param id 设备状态主键
     * @return 设备状态
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备状态列表
     *
     * @param device 设备状态
     * @return 设备状态
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备状态
     *
     * @param device 设备状态
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备状态
     *
     * @param device 设备状态
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备状态
     *
     * @param ids 需要删除的设备状态主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备状态信息
     *
     * @param id 设备状态主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200){
            throw new RuntimeException("同步产品列表失败");
        }
        redisTemplate.opsForValue().set(RedisKeyConstants.IOT_ALL_PRODUCT_LIST,response.getProducts());
        
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        List<ProductSummary> productSummaries =(List<ProductSummary>) redisTemplate.opsForValue().get(RedisKeyConstants.IOT_ALL_PRODUCT_LIST);
        if (ObjectUtil.isEmpty(productSummaries)){
            return CollectionUtil.empty(List.class);
        }
        List<ProductVo> productVos = BeanUtil.copyToList(productSummaries, ProductVo.class);
        return productVos;
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //1.判断设备名称name是否重复，（如果重复，抛出异常，终止运行）
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<Device>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapper)>0){
            throw new RuntimeException("设备名称重复");
        }
        //2.检验设备标识码nodeId是否重复
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getNodeId, deviceDto.getNodeId());
        if (count(queryWrapper1)>0){
            throw new RuntimeException("设备标识码重复");
        }
        //3.校验同一位置（位置类型+绑定位置）是否绑定了同一类产品(产品唯一标识)
        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Device::getLocationType, deviceDto.getLocationType());
        queryWrapper2.eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        queryWrapper2.eq(Device::getProductKey, deviceDto.getProductKey());
        queryWrapper2.eq(Device::getPhysicalLocationType , deviceDto.getPhysicalLocationType());
        if (count(queryWrapper2)>0){
            throw new RuntimeException("同一位置绑定了同一类产品");
        }
        //4.在iot平台中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setProductId(deviceDto.getProductKey());
        
        String str = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(str);
        addDevice.withAuthInfo(authInfo);
        
        request.withBody(addDevice);
        
        //5.设备数据保存到数据库
        String iotId = "";
        try {
            AddDeviceResponse response = client.addDevice(request);
            iotId = response.getDeviceId();
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(str);
        device.setIotId(iotId);
        save(device);
}

/**
 * 查询设备详细数据
 *
 * @param iotId
 * @return
 */
@Override
public DeviceDetailVo getDeviceDetail(String iotId) {
    Device device = getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
    if (ObjectUtil.isEmpty(device)){
        return null;
    }
    
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        String status = "";
        String activeTime = "";
        try {
            ShowDeviceResponse response = client.showDevice(request);
            status  = response.getStatus();
            activeTime = response.getActiveTime();
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询设备详细数据，调用失败");
        }
    DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
    detailVo.setDeviceStatus(status);
    if(ObjectUtil.isNotEmpty(activeTime)){
        LocalDateTime time = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
        //日期时区转换
         time = time.atZone(ZoneId.from(ZoneOffset.UTC))
                             .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                             .toLocalDateTime();
        detailVo.setActiveTime(time);
    }
    return detailVo;
}

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);
            Object properties = response.getShadow().get(0).getReported().getProperties();
            JSONObject entries = JSONUtil.parseObj(properties);
            String time = response.getShadow().get(0).getReported().getEventTime();
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(time, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = localDateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                                              .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                                              .toLocalDateTime();
            List<Map<String,Object>> list = new ArrayList<>();
            entries.forEach((k,v)->{
                Map<String,Object> map = new HashMap<>();
                map.put("functionId",k);
                map.put("value",v);
                map.put("eventTime",eventTime);
                list.add(map);
            });
            return list;
            
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查看设备上报的数据，调用失败");
        }
}

    /**
     * 修改设备
     *
     * @param deviceDto
     */
    @Override
    public void updateDeviceDto(DeviceDto deviceDto) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        body.withDescription(deviceDto.getDeviceDescription());
        request.withBody(body);
        try {
            UpdateDeviceResponse response = client.updateDevice(request);
                Device device = BeanUtil.toBean(deviceDto, Device.class);
                device.setDeviceName(response.getDeviceName());
                device.setDeviceDescription(response.getDescription());
                updateById(device);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public void deleteDevice(String iotId) {
        Device device = getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)){
            throw new BaseException("该设备不存在");
        }
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(device.getIotId());
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
            removeById(device.getId());
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
    }

    /**
     * 查询产品详情
     *
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        if (ObjectUtil.isEmpty(productKey)){
            return AjaxResult.error("产品ID不能为空");
        }
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        
        try {
            ShowProductResponse response = client.showProduct(request);
            List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
            if (ObjectUtil.isEmpty(serviceCapabilities)){
                return AjaxResult.success(List.of());
            }
            return AjaxResult.success(serviceCapabilities);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询产品详情，调用失败");
        }
        
    }
}
